/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：SearchListServlet   
 * 类描述：   搜索页
 * 创建人：zhanghl  
 * 创建时间：2016年11月18日 下午12:52:31   
 * 修改人：zhanghl   
 * 修改时间：2016年11月18日 下午12:52:31   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.SearchReqPara;
import com.lst.entity.response.SearchResPara;
import com.lst.model.Answer;
import com.lst.model.ClientNum;
import com.lst.model.Dynamic;
import com.lst.model.JiluLog;
import com.lst.model.MstClient;
import com.lst.model.MstGymnasium;
import com.lst.model.ProjectInfo;
import com.lst.model.Question;
import com.lst.model.VideoInfo;
import com.lst.model.WenwInfo;
import com.lst.service.AnswerService;
import com.lst.service.ClientNumService;
import com.lst.service.DynamicService;
import com.lst.service.JiluLogService;
import com.lst.service.MstClientService;
import com.lst.service.MstDiscussService;
import com.lst.service.ProjectInfoService;
import com.lst.service.QuestionService;
import com.lst.service.VideoInfoService;
import com.lst.service.WenwInfoService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: SearchListServlet
 * @Description: 搜索页
 * @author zhanghl
 * @date 2016年11月18日 下午12:52:31
 *
 */
public class SearchListServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

//	private WenwInfoService wenwInfoService = ctx.getBean(WenwInfoService.class);

//	private VideoInfoService videoInfoService = ctx.getBean(VideoInfoService.class);

//	private ProjectInfoService projectInfoService = ctx.getBean(ProjectInfoService.class);

	//private MstGymnasiumService mstGymnasiumService = ctx.getBean(MstGymnasiumService.class);

//	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);

	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	private DynamicService dynamicService = ctx.getBean(DynamicService.class);
	
	private QuestionService questionService = ctx.getBean(QuestionService.class);
	
	private MstClientService mstClientService = ctx.getBean(MstClientService.class);
	
	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);
	
	private JiluLogService jiluLogService = ctx.getBean(JiluLogService.class);
	
	private AnswerService answerService = ctx.getBean(AnswerService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		SearchResPara resPara = new SearchResPara();

		try {
			SearchReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				String searchwork = reqPara.getSearchwork();
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());
				Integer userid = Integer.valueOf(reqPara.getUserid());
				
				Map<String, Object> map = new HashMap<String, Object>();

				map.put("enabled", true);
				map.put("isDeleted", false);
				map.put("searchwork", searchwork);

				PageBounds pageBounds = new PageBounds(page,pagesize);					

			    List<MstClient> mstClientList = mstClientService.queryByList(map, pageBounds);
			    
			   
				//文章
//				List<WenwInfo> wilist = wenwInfoService.queryByList(map, pageBounds);
//
//				for(WenwInfo wi : wilist){
//					//收藏量
//					Integer favoritenum = CommFunUtils.opNum(null, wi.getId(), CommCode.SYSTEM_CARESEL_RANGE_WENW, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
//					//分享量
//					Integer sharenum = CommFunUtils.opNum(null, wi.getId(), CommCode.SYSTEM_CARESEL_RANGE_WENW, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
//					//浏览量
//					Map<String, Object> wenwmap = new HashMap<String, Object>();
//					
//					wenwmap.put("enabled", true);
//					wenwmap.put("isDeleted", false);	
//					wenwmap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
//					wenwmap.put("actid", wi.getId());
//					wenwmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_WENW);
//					
//					List<ClientNum> browselist = clientNumService.queryByList(wenwmap);
//					
//					//格式化时间
//					String wentime = DateUtil.getFormatTime(wi.getCreatedate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
//					wi.setWentime(wentime);
//					
//					Integer browsenum = 0;
//					
//					for(ClientNum c : browselist){
//						browsenum += c.getNum() == null ? 0 : c.getNum();
//					}
//					
//					wi.setFavoritenum(favoritenum);
//					wi.setSharenum(sharenum);
//					wi.setBrowsenum(browsenum);
//				}

				//视频
//				List<VideoInfo> vilist = videoInfoService.queryByList(map, pageBounds);
//
//				//评论量
//				Map<String, Object> videomap = new HashMap<String, Object>();
//
//				videomap.put("enabled", true);
//				videomap.put("isDleted", false);
//
//				for(VideoInfo vi : vilist){
//					//格式化时间
//					String videotime = DateUtil.getFormatTime(vi.getCreatedate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
//					vi.setVideotime(videotime);								
//					//评论量
//					videomap.put("tarid", vi.getId());
//
//					Integer videodiscussnum = mstDiscussService.queryCountByMap(videomap);
//
//					vi.setVideodiscussnum(videodiscussnum);
//
//					//收藏量
//					Integer favoritenum = CommFunUtils.opNum(null, vi.getId(), CommCode.SYSTEM_CARESEL_RANGE_VIDEO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
//					//分享量
//					Integer sharenum = CommFunUtils.opNum(null, vi.getId(), CommCode.SYSTEM_CARESEL_RANGE_VIDEO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
//					//浏览量
//					videomap.clear();
//					videomap.put("enabled", true);
//					videomap.put("isDeleted", false);	
//					videomap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
//					videomap.put("actid", vi.getId());
//					videomap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_VIDEO);
//					
//					List<ClientNum> browselist = clientNumService.queryByList(videomap);
//					
//					Integer browsenum = 0;
//					
//					for(ClientNum c : browselist){
//						browsenum += c.getNum() == null ? 0 : c.getNum();
//					}
//					
//					vi.setFavoritenum(favoritenum);
//					vi.setSharenum(sharenum);
//					vi.setBrowsenum(browsenum);
//				}					 

				//活动
//				List<ProjectInfo> pilist = projectInfoService.queryByList(map, pageBounds);
//
//				for(ProjectInfo pi : pilist){
//					//格式化时间
//					String starttime = StringUtils.isEmpty(pi.getStartdate()) ? null : DateUtil.getFormatTime(pi.getStartdate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
//					String endtime = StringUtils.isEmpty(pi.getEnddate()) ? null : DateUtil.getFormatTime(pi.getEnddate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
//					pi.setStarttime(starttime);			
//					pi.setEndtime(endtime);
//
//					//收藏量
//					Integer favoritenum = CommFunUtils.opNum(null, pi.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
//					//分享量
//					Integer sharenum = CommFunUtils.opNum(null, pi.getId(), CommCode.SYSTEM_CARESEL_RANGE_PRO, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
//					//浏览量
//					Map<String, Object> promap = new HashMap<String, Object>();
//					
//					promap.put("enabled", true);
//					promap.put("isDeleted", false);	
//					promap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
//					promap.put("actid", pi.getId());
//					promap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);
//					
//					List<ClientNum> browselist = clientNumService.queryByList(promap);
//					
//					Integer browsenum = 0;
//					
//					for(ClientNum c : browselist){
//						browsenum += c.getNum() == null ? 0 : c.getNum();
//					}
//					
//					pi.setFavoritenum(favoritenum);
//					pi.setSharenum(sharenum);
//					pi.setBrowsenum(browsenum);
//				}

				//场馆
				/*List<MstGymnasium> mglist = mstGymnasiumService.queryByList(map, pageBounds);

				for(MstGymnasium mg : mglist){
					//收藏量
					Integer favoritenum = CommFunUtils.opNum(null, mg.getId(), CommCode.SYSTEM_CARESEL_RANGE_GYM, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
					//分享量
					Integer sharenum = CommFunUtils.opNum(null, mg.getId(), CommCode.SYSTEM_CARESEL_RANGE_GYM, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
					//浏览量
					Map<String, Object> mgmap = new HashMap<String, Object>();
					
					mgmap.put("enabled", true);
					mgmap.put("isDeleted", false);	
					mgmap.put("numtype", CommCode.SYSTEM_COUNT_BROWSE);
					mgmap.put("actid", mg.getId());
					mgmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_GYM);
					
					List<ClientNum> browselist = clientNumService.queryByList(mgmap);
					
					Integer browsenum = 0;
					
					for(ClientNum c : browselist){
						browsenum += c.getNum() == null ? 0 : c.getNum();
					}
					
					mg.setFavoritenum(favoritenum);
					mg.setSharenum(sharenum);
					mg.setBrowsenum(browsenum);
				}*/
		//		List<MstGymnasium> mglist = new ArrayList<MstGymnasium>();
				
				//动态
				List<Dynamic> dyList=dynamicService.queryByList2(map, pageBounds);
				if(dyList!=null&&dyList.size()>0){
					for(Dynamic dynamic:dyList){
						Map<String, Object> dymap = new HashMap<String, Object>();
						dymap.put("enabled", true);
						dymap.put("isDeleted", false);
						dymap.put("tarid",dynamic.getDynamicId() );
						dymap.put("type", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
			            //评论数量
						Integer discussNum = mstDiscussService.queryCountByMap(dymap);
			            dynamic.setDiscussNum(discussNum);
			            
						 //喜欢数量
						Map<String, Object> mapjl = new HashMap<String, Object>();
				        mapjl.put("sourceId", dynamic.getDynamicId());
				        mapjl.put("jiluType", 1);
						int loveNum=jiluLogService.countBySourceId(mapjl);
						dynamic.setLoveNum(loveNum);
						
						//喜欢标识
						Map<String, Object> jilumap = new HashMap<String, Object>();
						jilumap.put("jiluType", 1);
						jilumap.put("isDelete", false);
						jilumap.put("sourceId", dynamic.getDynamicId());
						jilumap.put("createUser", userid);
						JiluLog jilu=jiluLogService.queryByMap(jilumap);
						if(jilu!=null){
							dynamic.setIsLove(jilu.getIsLove());
						}else{
							dynamic.setIsLove(false);
						}
						
						//标识是否收藏
						Map<String, Object> fmap = new HashMap<String, Object>();
						fmap.put("enabled", true);
						fmap.put("isdeleted", false);
						fmap.put("clientid", userid);
						fmap.put("actid", dynamic.getDynamicId());
						fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
						fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
						Integer count = clientNumService.queryCountByMap(fmap);
						if(count>0){
							dynamic.setIsFavorite(true);
						}else{
							dynamic.setIsFavorite(false);
						}
						
					
					}
				}
				
				
				//问题
			    List<Question> quList=questionService.queryByList(map, pageBounds);
			    if(quList!=null&&quList.size()>0){
			    	for(Question qu:quList){
						//标识是否回答过问题
						Map<String,Object> map2=new HashMap<String,Object>();
						map2.put("answerSourceId", qu.getQuestionId());
						map2.put("answerCreateUser", userid);
						Answer answer=answerService.selectByMap(map2);
						if(answer!=null){
							qu.setIsAnswer(true);
						}else{
							qu.setIsAnswer(false);
						}
						
						  //标识是否收藏
						Map<String, Object> fmap = new HashMap<String, Object>();
						fmap.put("enabled", true);
						fmap.put("isdeleted", false);
						fmap.put("clientid", userid);
						fmap.put("actid", qu.getQuestionId());
						fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_QUESTION);
						fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
						Integer count = clientNumService.queryCountByMap(fmap);
						if(count>0){
							qu.setIsFavorite(true);
						}else{
							qu.setIsFavorite(false);
						}
						
			    	}
			    }
			    
			  //回答
			   List<Answer> anList=answerService.queryByList(map, pageBounds);
			   if(anList!=null&&anList.size()>0){
					for(Answer an:anList){
						//评论量
						Map<String, Object> anmap = new HashMap<String, Object>();
						anmap.put("tarid", an.getAnswerId());
						anmap.put("type", 50);
						Integer answerDiscussNum = mstDiscussService.queryCountByMap(anmap);
						an.setAnswerDiscussNum(answerDiscussNum);
						
						//喜欢标识
						Map<String, Object> jilumap2 = new HashMap<String, Object>();
						jilumap2.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_ANSWER);
						jilumap2.put("isDelete", false);
						jilumap2.put("sourceId", an.getAnswerId());
						jilumap2.put("createUser", userid);
						JiluLog jilu=jiluLogService.queryByMap(jilumap2);
						if(jilu!=null){
							an.setIsLove(jilu.getIsLove());
						}else{
							an.setIsLove(false);
						}
						
					  //喜欢数量
						Map<String, Object> jlmap2 = new HashMap<String, Object>();
						jlmap2.put("sourceId", an.getAnswerId());
						jlmap2.put("jiluType", 2);
						int loveNum=jiluLogService.countBySourceId(jlmap2);
						an.setAnswerLoveNum(loveNum);
					}
				}
				
			    resPara.setMstClientlist(mstClientList);
				resPara.setDylist(dyList);
				resPara.setQulist(quList);
				resPara.setAnlist(anList);
//				resPara.setWilist(wilist);
//				resPara.setVilist(vilist);
//				resPara.setPilist(pilist);
//				resPara.setMglist(mglist);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info("SearchListServlet jsonResult:" +jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public SearchReqPara getReqPara(HttpServletRequest request) {

		SearchReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new SearchReqPara());

			reqPara = (SearchReqPara) baseRequest.clone();

			String searchwork = request.getParameter("searchwork");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
			String userid = request.getParameter("userid");

//			logger.info("reqPara searchwork: " + searchwork);
//			logger.info("reqPara page: " + page);
//			logger.info("reqPara pagesize: " + pagesize);

			reqPara.setSearchwork(searchwork);
			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);
			reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		SearchReqPara piReqPara = (SearchReqPara) reqPara;
		SearchResPara piResPara = (SearchResPara) resPara;

		if(StringUtils.isEmpty(piReqPara.getSearchwork())){
			piResPara.setCode(CommCode.M_A000000);
			piResPara.setMessage(CommCode.M_F000001);
		}else if(StringUtils.isEmpty(piReqPara.getPage())){
			piResPara.setCode(CommCode.M_A000000);
			piResPara.setMessage(CommCode.M_P000009);
		}else if(StringUtils.isEmpty(piReqPara.getUserid())){
			piResPara.setCode(CommCode.M_A000000);
			piResPara.setMessage(CommCode.M_P000002);
		} else if(StringUtils.isEmpty(piReqPara.getPagesize())){
			piResPara.setCode(CommCode.M_A000000);
			piResPara.setMessage(CommCode.M_P000010);
		} else {
			flag = true;
		}

		return  flag;
	}
}
